#! /usr/bin/env python3
#! -*- encoding:utf-8 -*-
import asyncio
import threading

@asyncio.coroutine
def hello():
    print("hello world(%s)" % threading.currentThread())
    r = yield from asyncio.sleep(1)
    print("hello again(%s)" % threading.currentThread())

# 版本3.5后
async def helloAsync():
    print("hello world(%s)" % threading.currentThread())
    r = await asyncio.sleep(1)
    print("hello again(%s)" % threading.currentThread())


@asyncio.coroutine
def wget(host):
    print("wget %s" % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = yield from connect
    header = 'GET / HTTP/1.0\r\nHost:%s\r\n\r\n' % host
    writer.write(header.encode("utf8"))
    yield from writer.drain()
    while True:
        line = yield from reader.readline()
        if line == b'\r\n':
            break
        print('%s header %s' % (host, line.decode("utf8").rstrip()))
    writer.close()

# 版本3.5后
async def wgetAsync(host):
    print("wget %s" % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = await connect
    header = 'GET / HTTP/1.0\r\nHost:%s\r\n\r\n' % host
    writer.write(header.encode("utf8"))
    await writer.drain()
    while True:
        line = await reader.readline()
        if line == b'\r\n':
            break
        print('%s header %s' % (host, line.decode("utf8").rstrip()))
    writer.close()


loop = asyncio.get_event_loop()
#task = [hello(), hello()]
task = [helloAsync(), wgetAsync("www.baidu.com"), wgetAsync("xqn.njlime.com"), wgetAsync("www.tmall.com")]
loop.run_until_complete(asyncio.wait(task))
loop.close()